package com.rising.face.ali.bishi.binary;

/**
 * @Author: rising
 * @Description: 给你两个二进制字符串，返回它们的和（用二进制表示）。
 *                  输入为 非空 字符串且只包含数字 1 和 0。
 * @Date: create in 2021/2/27 9:57
 */
public class BinarySum {
    public static void main(String[] args) {
        String a = "11", b = "1";
        System.out.println(a + " + " + b + " = " + addBinary(a, b));
        a = "1010";b = "1011";
        System.out.println(a + " + " + b + " = " + addBinary(a, b));
    }

    public static String addBinary(String a, String b) {
        StringBuilder ans = new StringBuilder();
        int ca = 0;
        for(int i = a.length() - 1, j = b.length() - 1;i >= 0 || j >= 0; i--, j--) {
            int sum = ca;
            sum += i >= 0 ? a.charAt(i) - '0' : 0;
            sum += j >= 0 ? b.charAt(j) - '0' : 0;
            ans.append(sum & 1);
            ca = sum / 2;
        }
        ans.append(ca == 1 ? ca : "");
        return ans.reverse().toString();
    }


    public static String sumBinary(String a, String b) {
        int alength = a.length();
        int blength = b.length();

        //以下是将短的补0
        if (alength > blength) {
            b = addStr(b, alength - blength);
        }
        if (blength > alength) {
            a = addStr(a, blength - alength);
        }

        String rtnStr = "";
        char temp = '0';
        char[] achars = a.toCharArray();
        char[] bchars = b.toCharArray();


        for (int i = achars.length - 1; i >=0 ; i--) {
            if ((achars[i] == '1' && bchars[i] == '0' && temp == '0')
                    || (achars[i] == '0' && bchars[i] == '1' && temp == '0')
                    || (achars[i] == '0' && bchars[i] == '0' && temp == '1')) {
                rtnStr = "1" + rtnStr;
                temp = '0';
                continue;
            }
            if ((achars[i] == '1' && bchars[i] == '1' && temp == '0')
                    || (achars[i] == '0' && bchars[i] == '1' && temp == '1')
                    || (achars[i] == '1' && bchars[i] == '0' && temp == '1')) {
                rtnStr = "0" + rtnStr;
                temp = '1';
                continue;
            }

            if (achars[i] == '1' && bchars[i] == '1' && temp == '1') {
                rtnStr = "1" + rtnStr;
                temp = '1';
                continue;
            }

            if (achars[i] == '0' && bchars[i] == '0' && temp == '0') {
                rtnStr = "0" + rtnStr;
                temp = '0';
                continue;
            }
        }

        if (temp == '1') {
            rtnStr = "1" + rtnStr;
        }
        return rtnStr;
    }

    //补0操作
    public static String addStr(String str, int length) {
        for (int i = 0; i < length; i++) {
            str = "0" + str;
        }
        return str;
    }
}
